import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:path/path.dart' as path;
import 'package:flutter/material.dart';
import 'package:top_foundation/utils/theme/button.dart';
import 'package:top_foundation/utils/theme/theme.dart';
import 'package:wechat_kit/wechat_kit.dart';
import 'package:whale/helper/utils/httputils/http_man.dart';

import 'popup/index.dart';
import 'util.dart';

enum ShareType {
  wx,
  timeline,
}

class Wxman {
  static final Wxman instance = Wxman._inverval();
  factory Wxman() => instance;
  Wxman._inverval() {
    init();
  }
  init() {
    _respSubs = WechatKitPlatform.instance.respStream().listen(_listenResp);
    WechatKitPlatform.instance.handleInitialWXReq();
  }

  late final StreamSubscription<WechatResp> _respSubs;
  WechatAuthResp? _authResp;

  Future<void> register() async {
    // final result = await fluwx.registerApi(
    //     appId: 'wx4e5fa8fac75f5b56', universalLink: 'https://www.whale.com');
    // Get.log(result ? '注册成功' : '注册失败');
    // fluwx.authBy(which: NormalAuth(scope: 'snsapi_userinfo'));
    await WechatKitPlatform.instance.registerApp(
        appId: 'wx4e5fa8fac75f5b56', universalLink: 'https://www.whale.com');
  }

  void _listenResp(WechatResp resp) {
    if (resp is WechatAuthResp) {
      _authResp = resp;
      if (resp.errorCode != 0) {
        Hud.toast(resp.errorMsg ?? '');
      }
    } else if (resp is WechatShareMsgResp) {
      if (resp.errorCode != 0) {
        Hud.toast(resp.errorMsg ?? '');
      }
    } else if (resp is WechatPayResp) {
      if (resp.errorCode != 0) {
        Hud.toast(resp.errorMsg ?? '');
      }
    } else if (resp is WechatLaunchMiniProgramResp) {
      if (resp.errorCode != 0) {
        Hud.toast(resp.errorMsg ?? '');
      }
    }
  }

  void dispose() {
    _respSubs.cancel();
  }

  void wxreq() async {}

  Future<void> wxLogin() {
    return WechatKitPlatform.instance.auth(
      scope: <String>[WechatScope.kSNSApiUserInfo],
      state: 'auth',
    );
  }

  static Future<void> shareText({
    required String content,
  }) async {
    // fluwx.share(WeChatShareTextModel('source'));
    final scene = await _pop();
    if (scene == null) return;
    await WechatKitPlatform.instance.shareText(scene: scene, text: content);
  }

  static Future<void> shareImg({
    required String title,
    required String des,
    required Uint8List image,
    Uint8List? thumb,
  }) async {
    final scene = await _pop();
    if (scene == null) return;

    await WechatKitPlatform.instance.shareImage(
      scene: WechatScene.kSession,
      title: title,
      description: des,
      thumbData: thumb,
      imageData: image,
    );
  }

  static Future<void> shareFile({
    required String title,
    required String des,
    required String url,
  }) async {
    // fluwx.share(WeChatShareTextModel('source'));
    final scene = await _pop();
    if (scene == null) return;
    Uri? file;
    if (url.startsWith('http')) {
      final uri = Uri.parse(url);
      final savePath = await FileManager().tempPath(uri.pathSegments.last);
      await HttpMan().download(url, savePath);
      file = Uri.file(savePath);
    } else {
      file = Uri.file(url);
    }

    await WechatKitPlatform.instance.shareFile(
      scene: WechatScene.kSession,
      title: title,
      description: des,
      fileUri: file,
      fileExtension: path.extension(file.path),
    );
  }

  static Future<void> shareWeb({
    required String title,
    required String des,
    required String url,
    ui.Image? thumb,
  }) async {
    // fluwx.share(WeChatShareTextModel('source'));
    final scene = await _pop();
    if (scene == null) return;
    final byteData = await thumb?.toByteData();
    await WechatKitPlatform.instance.shareWebpage(
      scene: scene,
      title: title,
      description: des,
      thumbData: byteData?.buffer.asUint8List(),
      webpageUrl: url,
    );
  }

  static Future<int?> _pop() async {
    final isInstalled = await WechatKitPlatform.instance.isInstalled();
    if (!isInstalled) {
      return null;
    }
    final action = await Popup.bottom<int>(child: const _ShareView());
    if (action == 0) {
      return WechatScene.kSession;
    }
    if (action == 1) {
      return WechatScene.kTimeline;
    }
    return null;
  }

  // static Future<bool> _share(WeChatShareModel m) async {
  //   final res = await fluwx.share(m);
  //   if (!res) {
  //     Hud.toast('取消');
  //   }
  //   return res;
  // }
}

class _ShareView extends StatelessWidget {
  const _ShareView();
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
            color: ITheme.backgroundColor,
            borderRadius: BorderRadius.vertical(top: Radius.circular(15.r)),
          ),
          padding: EdgeInsets.all(20.r),
          child: SeparatorRow(
            children: [
              IButton.create(
                  onPressed: () {
                    Get.back(result: 0);
                  },
                  child: IButtonContent(
                    icon: ClipOval(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Colors.white,
                        ),
                        alignment: Alignment.center,
                        padding: EdgeInsets.all(10.r),
                        child: Image.asset(
                          'wx.png'.imgPathCommon,
                          width: 30.r,
                          height: 30.r,
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                    text: '微信',
                    fontSize: 12.sp,
                  )),
              IButton.create(
                  onPressed: () {
                    Get.back(result: 1);
                  },
                  child: IButtonContent(
                    icon: ClipOval(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Colors.white,
                        ),
                        alignment: Alignment.center,
                        padding: EdgeInsets.all(10.r),
                        child: Image.asset(
                          'wx_circle.png'.imgPathCommon,
                          width: 30.r,
                          height: 30.r,
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                    text: '朋友圈',
                    fontSize: 12.sp,
                  )),
            ],
            separatorBuilder: (index) => SizedBox(width: 25.r),
          ),
        ),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: Get.back,
          child: Container(
            width: double.infinity,
            color: Colors.white,
            child: SafeArea(
              top: false,
              child: Container(
                height: 44.r,
                alignment: Alignment.center,
                child: Text(
                  '取消',
                  style: ITheme.text.titleMedium,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
